package cm.tl.pms.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 参数校验相关的全部工具类
 *
 * @author w7h1te_ywq
 * @version 1.0.0
 * @date 2023-11-02 16:11
 */
@Slf4j
public class ValidateUtil {

    /**
     * 解析JSON字符串到指定的实体类对象
     *
     * @param content 要解析的JSON字符串
     * @param clazz   指定的实体类对象
     * @return 解析成功返回一个实体类对象，解析失败返回null
     */
    public static <T> T parseJson(String content, Class<T> clazz) {
        try {
            return JSON.parseObject(content, clazz);
        } catch (Exception e) {
            log.error("解析失败：{}", e.getMessage());
            return null;
        }
    }


    /**
     * 校验指定的实体类对象
     *
     * @param object 要校验的实体类对象  (实体中包含 @NotBlank的)
     * @return 返回一个包含所有错误信息的List，如果校验通过则返回空列表
     */
    public static <T> List<String> validateEntity(T object) {
        List<String> errorMessages = new ArrayList<>();

        // 使用javax.validation进行校验
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> violations = validator.validate(object);

        if (!violations.isEmpty()) {
            // 校验失败，收集错误信息
            for (ConstraintViolation<T> violation : violations) {
                errorMessages.add(violation.getMessage());
            }
        }

        return errorMessages;
    }

    public static boolean isExpired(Date expiresIn) {
        if (expiresIn != null) {
            long sendTime = expiresIn.getTime();
            long nowTime = System.currentTimeMillis();
            long diff = nowTime - sendTime;
            long minute = diff / (1000 * 60);

            return minute >= 1;
        }

        return false;
    }

}
